from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from activity.models import Activity, SignUp
from activity.serializers import ActivityListSerializer, ActivityRetrieveSerializer, ActivityApplySerializer


class ActivityViewSet(ReadOnlyModelViewSet):
    queryset = Activity.objects.filter(on_deleted=False).order_by('-published_time')

    def get_serializer_class(self):
        if self.action == "list":
            return ActivityListSerializer
        else:
            return ActivityRetrieveSerializer

    def list(self, request, *args, **kwargs):
        # 判断用户是否登录
        if request.user.is_authenticated():
            user_id = request.user.id
            # 根据用户id查询活动报名模型对象
            applies = SignUp.objects.filter(user_id=user_id)
            activity_sign_up_id_li = []
            for apply in applies:
                activity_id = apply.activity_id
                activity_sign_up_id_li.append(activity_id)
            # print(activity_sign_up_id_li)

            # 判断
            activities = self.get_queryset()
            for activity in activities:
                if activity.id in activity_sign_up_id_li:
                    activity.is_apply=True
                    activity.save()

        # 用户未登录活动is_apply全部为False
        else:
            activities = self.get_queryset()
            for activity in activities:
                activity.is_apply=False
                activity.save()

        # 调用父类方法list
        return super().list(request, *args, **kwargs)


class ActivityApplyView(GenericAPIView):
    # 设置权限
    permission_classes = [IsAuthenticated]
    serializer_class = ActivityApplySerializer

    def post(self, request):
        # 创建序列化器对象对象
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)





